import React, { useState, useEffect } from 'react';
import './CourseList.css';
import { fetchCourseList } from '../utils/request/request';

// 定义课程数据类型
type Course = {
  id: number;
  title: string;
  subtitle: string;
  cover: string;
  price: string;
  lessons: number;
  playerCount: string;
  firstEpLabel?: string;
  firstEpTitle?: string;
  link: string;
};

interface CourseListProps {
  params: {
    classification_id: number;
    sort_type: number;
    page_size: number;
    page: number;
    word: string;
  };
  setParams: React.Dispatch<React.SetStateAction<{
    classification_id: number;
    sort_type: number;
    page_size: number;
    page: number;
    word: string;
  }>>;
}

const CourseList: React.FC<CourseListProps> = ({ params, setParams }) => {
  // 定义组件状态
  const [mode, setMode] = useState<'big' | 'small'>('big'); // 切换显示模式
  const [items, setItems] = useState<Course[]>([]); // 课程列表
  const [extraCourses, setExtraCourses] = useState<Course[]>([]); // 额外推荐课程
  const [pageInfo, setPageInfo] = useState({ num: 1, size: 30, total: 0, next: false }); // 分页信息
  const [inputPage, setInputPage] = useState<string>(''); // 跳转页码输入框

  // 获取课程列表数据
  useEffect(() => {
    fetchCourseList(params)
      .then((res) => {
        // 解析返回数据
        const itemsRaw = res?.data?.items || [];
        const extraRaw = res?.data?.extra_data?.extra_items || [];
        const page = res?.data?.page || { num: 1, size: 30, total: 0, next: false };
        setPageInfo(page);
        setItems(
          itemsRaw.map((item: any) => ({
            id: item.seasonId,
            title: item.title,
            subtitle: item.subtitle,
            cover: item.cover,
            price:
              item.price_format_show && item.price_format_show.endsWith('元')
                ? item.price_format_show
                : (item.price_format ? item.price_format + ' 元' : ''),
            lessons: item.ep_count,
            playerCount: item.stat?.view || '',
            firstEpLabel: item.first_ep_label || '',
            firstEpTitle: item.first_ep_title || '',
            link: item.link,
          }))
        );
        setExtraCourses(
          extraRaw.map((item: any) => ({
            id: item.seasonId,
            title: item.title,
            subtitle: item.subtitle,
            cover: item.cover,
            price:
              item.price_format_show && item.price_format_show.endsWith('元')
                ? item.price_format_show
                : (item.price_format ? item.price_format + ' 元' : ''),
            lessons: item.ep_count,
            playerCount: item.stat?.view || '',
            firstEpLabel: item.first_ep_label || '',
            firstEpTitle: item.first_ep_title || '',
            link: item.link,
          }))
        );
      })
      .catch(() => {
        // 错误处理
        setItems([]);
        setExtraCourses([]);
        setPageInfo({ num: 1, size: 30, total: 0, next: false });
      });
  }, [params]);

  // 高亮搜索关键词
  const highlightKeyword = (title: string) => {
    const parser = new DOMParser();
    const decodedTitle = parser.parseFromString(title, 'text/html').body.innerHTML || '';
    return decodedTitle;
  };

  return (
    <div>
      <div className="result-wrp">
        {/* 切换显示模式按钮 */}
        <div className="result-header">
          <div className="mode-trigger">
            <span
              className={`big-mode${mode === 'big' ? ' active' : ''}`}
              onClick={() => setMode('big')}
            >
              {/* big mode svg */}
              <svg width="14" height="14" viewBox="0 0 14 14">
                <g fill="none" fillRule="evenodd">
                  <rect x="0" y="0" width="6.22" height="6.22" rx="1" />
                  <rect x="0" y="7.78" width="6.22" height="6.22" rx="1" />
                  <path d="M8.56,0.78h4.67c0.43,0,0.78,0.35,0.78,0.78s-0.35,0.78-0.78,0.78H8.56c-0.43,0-0.78-0.35-0.78-0.78S8.13,0.78,8.56,0.78z" />
                  <path d="M8.56,8.56h4.67c0.43,0,0.78,0.35,0.78,0.78s-0.35,0.78-0.78,0.78H8.56c-0.43,0-0.78-0.35-0.78-0.78S8.13,8.56,8.56,8.56z" />
                  <path d="M8.56,3.89h4.67c0.43,0,0.78,0.35,0.78,0.78s-0.35,0.78-0.78,0.78H8.56c-0.43,0-0.78-0.35-0.78-0.78S8.13,3.89,8.56,3.89z" />
                  <path d="M8.56,11.67h4.67c0.43,0,0.78,0.35,0.78,0.78s-0.35,0.78-0.78,0.78H8.56c-0.43,0-0.78-0.35-0.78-0.78S8.13,11.67,8.56,11.67z" />
                </g>
              </svg>
            </span>
            <span
              className={`small-mode${mode === 'small' ? ' active' : ''}`}
              onClick={() => setMode('small')}
            >
              {/* small mode svg */}
              <svg width="14" height="14" viewBox="0 0 14 14">
                <g fill="#0BA395">
                  <rect x="0" y="0" width="6.22" height="6.22" rx="1" />
                  <rect x="7.78" y="0" width="6.22" height="6.22" rx="1" />
                  <rect x="0" y="7.78" width="6.22" height="6.22" rx="1" />
                  <rect x="7.78" y="7.78" width="6.22" height="6.22" rx="1" />
                </g>
              </svg>
            </span>
          </div>
        </div>
        {/* 课程列表展示 */}
        <div className="items-section">
          {items.length > 0 ? (
            <div className={`season-list ${mode}-mode`}>
              {mode === 'big' && (
                <div className="big-mode">
                  {items.map((item, index) => (
                    <div
                      key={index}
                      className="big-card-wrp big-card"
                    >
                      <a href={item.link} target="_blank" rel="noopener noreferrer">
                        <div className="cover-img">
                          <img
                            src={item.cover}
                            alt={item.title}
                            className="block-list-lazyImg"
                            referrerPolicy="no-referrer"
                          />
                          <div className="block-list-item-info-mask"></div>
                          <div className="block-list-item-info">
                            <div className="block-list-item-info-player">
                              <img
                                className="block-list-item-info-player--img"
                                src=""
                                alt="player"
                              />
                              <span>{item.playerCount}</span>
                            </div>
                            <p>共{item.lessons}课时</p>
                          </div>
                        </div>
                        <div className="title">
                          <span dangerouslySetInnerHTML={{ __html: highlightKeyword(item.title) }}></span>
                        </div>
                        <div className="subtitle">{item.subtitle}</div>
                        <p className="block-list-item-price"><span>{item.price}</span></p>
                        {item.firstEpLabel || item.firstEpTitle ? (
                          <div className="first-ep">
                            <span className="play-btn"></span>
                            {item.firstEpLabel && <span className="first-ep-label">{item.firstEpLabel}</span>}
                            {item.firstEpTitle && <span className="first-ep-title">{item.firstEpTitle}</span>}
                          </div>
                        ) : null}
                      </a>
                    </div>
                  ))}
                </div>
              )}
              {mode === 'small' && (
                <div className="small-mode">
                  {items.map((item, index) => (
                    <div
                      key={index}
                      className="block-list-item small-card"
                      style={{
                        width: 'calc(20% - 16px)',
                        marginBottom: '24px',
                        marginRight: '16px',
                      }}
                    >
                      <a href={item.link} target="_blank" rel="noopener noreferrer">
                        <div className="block-list-item-img">
                          <img
                            src={item.cover}
                            alt={item.title}
                            className="block-list-lazyImg"
                            referrerPolicy="no-referrer"
                          />
                          <div className="block-list-item-info-mask"></div>
                          <div className="block-list-item-info">
                            <div className="block-list-item-info-player">
                              <img
                                className="block-list-item-info-player--img"
                                src=""
                                alt="player"
                              />
                              <span>{item.playerCount}</span>
                            </div>
                            <p>共{item.lessons}课时</p>
                          </div>
                        </div>
                        <p className="block-list-item-title ell">
                          <span dangerouslySetInnerHTML={{ __html: highlightKeyword(item.title) }}></span>
                        </p>
                        <p className="block-list-item-desc ell">{item.subtitle}</p>
                        <p className="block-list-item-price">
                          <span>{item.price}</span>
                        </p>
                      </a>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <div className="empty-state">
              <img
                src="//s1.hdslb.com/bfs/static/jinkela/edu-pc/pages/assets/empty_result.png"
                alt="空状态"
              />
              <p className="txt">搜索结果为空</p>
            </div>
          )}
        </div>
        <div className="extra-items-section">
          {extraCourses.length > 0 && <div className="more-recommend-title">更多推荐</div>}
          {mode === 'big' && (
            <div className="big-mode">
              {extraCourses.map((course, idx) => (
                <div
                  key={course.id}
                  className="big-card-wrp big-card"
                  style={{
                    width: 'calc(50% - 16px)', 
                    marginBottom: '24px',
                    marginRight: (idx + 1) % 2 === 0 ? '0' : '16px',
                  }}
                >
                  <a href={course.link} target="_blank" rel="noopener noreferrer">
                    <div className="cover-img">
                      <img
                        src={course.cover}
                        alt={course.title}
                        className="block-list-lazyImg"
                        referrerPolicy="no-referrer"
                      />
                      <div className="block-list-item-info-mask"></div>
                      <div className="block-list-item-info">
                        <div className="block-list-item-info-player">
                          <img
                            className="block-list-item-info-player--img"
                            src=""
                            alt="player"
                          />
                          <span>{course.playerCount}</span>
                        </div>
                        <p>共{course.lessons}课时</p>
                      </div>
                    </div>
                    <div className="title">
                      <span dangerouslySetInnerHTML={{ __html: highlightKeyword(course.title) }}></span>
                    </div>
                    <div className="subtitle">{course.subtitle}</div>
                    <p className="block-list-item-price"><span>{course.price}</span></p>
                    {course.firstEpLabel || course.firstEpTitle ? (
                      <div className="first-ep">
                        <span className="play-btn"></span>
                        {course.firstEpLabel && <span className="first-ep-label">{course.firstEpLabel}</span>}
                        {course.firstEpTitle && <span className="first-ep-title">{course.firstEpTitle}</span>}
                      </div>
                    ) : null}
                  </a>
                </div>
              ))}
            </div>
          )}
          {mode === 'small' && (
            <div className="small-mode">
              {extraCourses.map((course, idx) => (
                <div
                  key={course.id}
                  className="block-list-item small-card"
                  style={{
                    width: 'calc(20% - 16px)', 
                    marginBottom: '24px',
                    marginRight: (idx + 1) % 5 === 0 ? '0' : '16px', 
                  }}
                >
                  <a href={course.link} target="_blank" rel="noopener noreferrer">
                    <div className="block-list-item-img">
                      <img
                        src={course.cover}
                        alt={course.title}
                        className="block-list-lazyImg"
                        referrerPolicy="no-referrer"
                      />
                      <div className="block-list-item-info-mask"></div>
                      <div className="block-list-item-info">
                        <div className="block-list-item-info-player">
                          <img
                            className="block-list-item-info-player--img"
                            src=""
                            alt="player"
                          />
                          <span>{course.playerCount}</span>
                        </div>
                        <p>共{course.lessons}课时</p>
                      </div>
                    </div>
                    <p className="block-list-item-title ell">
                      <span dangerouslySetInnerHTML={{ __html: highlightKeyword(course.title) }}></span>
                    </p>
                    <p className="block-list-item-desc ell">{course.subtitle}</p>
                    <p className="block-list-item-price">
                      <span>{course.price}</span>
                    </p>
                  </a>
                </div>
              ))}
            </div>
          )}
        </div>
        {/* 分页组件 */}
        <div className="pager-wrp">
          <div className="pager">
            <div className="pages">
              {params.page > 1 && (
                <span className="page-item">
                  <button onClick={() => setParams((prev) => ({ ...prev, page: params.page - 1 }))}>上一页</button>
                </span>
              )}
              {params.page > 2 && (
                <span className="page-item">
                  <button onClick={() => setParams((prev) => ({ ...prev, page: 1 }))}>1</button>
                </span>
              )}
              {params.page > 3 && <span className="page-item ellipsis">...</span>}
              {[params.page - 1, params.page, params.page + 1]
                .filter((page) => page > 0 && page <= Math.ceil(pageInfo.total / pageInfo.size))
                .map((page) => (
                  <span
                    key={page}
                    className={`page-item ${params.page === page ? 'active' : ''}`}
                  >
                    <button onClick={() => setParams((prev) => ({ ...prev, page }))}>{page}</button>
                  </span>
                ))}
              {params.page < Math.ceil(pageInfo.total / pageInfo.size) - 2 && <span className="page-item ellipsis">...</span>}
              {params.page < Math.ceil(pageInfo.total / pageInfo.size) - 1 && (
                <span className="page-item">
                  <button onClick={() => setParams((prev) => ({ ...prev, page: Math.ceil(pageInfo.total / pageInfo.size) }))}>
                    {Math.ceil(pageInfo.total / pageInfo.size)}
                  </button>
                </span>
              )}
              {params.page < Math.ceil(pageInfo.total / pageInfo.size) && (
                <span className="page-item">
                  <button onClick={() => setParams((prev) => ({ ...prev, page: params.page + 1 }))}>下一页</button>
                </span>
              )}
            </div>
            <div className="jump-pager">
              <span className="page-total">共{Math.ceil(pageInfo.total / pageInfo.size)}页，跳至</span>
              <input
                type="text"
                onChange={(e) => setInputPage(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    const page = parseInt(inputPage, 10);
                    if (!isNaN(page) && page > 0 && page <= Math.ceil(pageInfo.total / pageInfo.size)) {
                      setParams((prev) => ({ ...prev, page }));
                    }
                  }
                }}
                value={inputPage}
                placeholder=""
              />
              <span className="page-text">页</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CourseList;